package org.testis.data.parser;

import org.testis.data.AtofModuleConstants;
import org.testis.logging.AtofLogLevel;
import org.testis.logging.LogSenderService;
import org.testis.testdriver.TestPlanGlobalsHashMap;
import org.testis.testdriver.TestStepGlobalDataHashMap;
import org.testis.testdriver.translation.AtofValueTranslateService;
import org.testis.webautomationmodule.data.WebAutomationModuleDataObject;
import org.testis.webautomationmodule.ui.UIEnumaration.UIObjectParameter;
import org.testis.webautomationmodule.ui.UIEnumaration.UIObjectType;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import org.testis.orm.refinedclasses.DynamicMapDesignTreeNode;
import org.testis.orm.refinedclasses.DynamicMapObject;
import org.testis.orm.refinedclasses.DynamicMapParameter;

/**
 *
 * @author nurhat
 */
public class WAMLoginDopDecorator extends WAMDopDecorator {

    public WAMLoginDopDecorator(
            WebAutomationModuleDataObject data,
            DynamicMapDesignTreeNode root) {
        super(data,
                root);
    }

    @Override
    protected boolean setBehavior() {
        LogSenderService.putMessageOnQueue("WebAutomationDataObjectParser",
                AtofLogLevel.INFO,
                "Appending login policy to WebAutomationDataObject ",
                getData().getMessageId());

        ArrayList<DynamicMapDesignTreeNode> lst =
                new ArrayList<DynamicMapDesignTreeNode>();
        DynamicMapObject obj = getRoot().getObject();
        DynamicMapParameter parLoginPageId =
                obj.getParameterByName(UIObjectParameter.LoginPageId.name());
        String loginPageId = "";
        if (parLoginPageId == null) {
            LogSenderService.putMessageOnQueue("WebAutomationDataObjectParser",
                    AtofLogLevel.ERROR,
                    "Login page not found.Check DynamicMap root node!!!",
                    getData().getMessageId());
            return false;
        }
        loginPageId = parLoginPageId.getValue();
        DynamicMapDesignTreeNode page = null;
        if (loginPageId != null) {
            if (!loginPageId.equals("")) {
                page = findObject(loginPageId);
            }
        }
        if (page == null) {
            LogSenderService.putMessageOnQueue("WebAutomationDataObjectParser",
                    AtofLogLevel.ERROR,
                    "Login page not found.Check DynamicMap root node!!!",
                    getData().getMessageId());
            return false;
        }

        findLoginPageObjects(lst,
                page);
        ArrayList<DynamicMapDesignTreeNode> lstSorted =
                sortloginPageObjects(lst);

        if (getData().getDataToApply() != null) {
            applyLoginDataIfExists(lstSorted);
        }

        appendObjectsToList(lstSorted,
                getData().getLoginDataList());
        return true;
    }

    private void applyLoginDataIfExists(ArrayList<DynamicMapDesignTreeNode> list) {
        Set keys = getData().getDataToApply().keySet();
        Iterator It = keys.iterator();
        String abstractId;
        DynamicMapParameter abstractParameter;
        DynamicMapParameter valueParam;
        String absIdOfPassField = "__asp_login_password_txt";
        AtofValueTranslateService service = new AtofValueTranslateService(
                    TestPlanGlobalsHashMap.createInstance().getTestplanglobals(),
                    TestPlanGlobalsHashMap.createInstance().getTestplanlanguages(),
                    TestPlanGlobalsHashMap.createInstance().getTestplandutvalues(),
                    TestStepGlobalDataHashMap.createInstance().getTeststepglobals());
        try {
            absIdOfPassField = service.translateValue("@GLOBAL_AbsId_Of_LoginPagePasswordField@");
        } catch (Exception ex) {
        }
        while (It.hasNext()) {
            String current = (String) (It.next());
            for (int i = 0; i < list.size(); i++) {
                abstractParameter =
                        list.get(i).getObject().getParameterByName(
                        UIObjectParameter.AbstractId.name());
                valueParam =
                        list.get(i).getObject().getParameterByName(
                        UIObjectParameter.Value.name());
                abstractId = getParameterValue(abstractParameter);

                if (valueParam != null) {
                    valueParam.setRunTimeValue(null);
                    try {
                        String valTranslated = service.translateValue(valueParam.getReference().getValue());
                        valueParam.setRunTimeValue(valTranslated);
                    } catch (Exception ex) {
                    }
                }
                if (abstractId != null) {
                    if (abstractId.equals(absIdOfPassField)) {
                        String passFields = service.translateValue("@GLOBAL_AbsIds_Of_PasswordFields@");
                        String[] arrPassFields = passFields.split(AtofModuleConstants.PARAM_SEP_SPLIT_STR);
                        String newPassWordValue = null;
                        for (int index = 0; index < arrPassFields.length; index++) {
                            String newpassWordTxt = "#USEMAP" + arrPassFields[index] + "#";
                            try {
                                newPassWordValue = service.translateValue(newpassWordTxt);
                            } catch (Exception ex) {
                            }
                            if (newPassWordValue != null) {
                                break;
                            }
                        }
                        if (newPassWordValue != null) {
                            valueParam.setRunTimeValue(newPassWordValue);
                        }
                    }
                }
                if (current.equals(abstractId)) {
                    if (valueParam != null) {
                        try {
                            String valTranslated = service.translateValue(getData().getDataToApply().get(
                                    current));
                            valueParam.setRunTimeValue(valTranslated);
                        } catch (Exception ex) {
                        }

                    }
                    getData().getDataToApply().remove(current);
                }
            }
        }
    }

    private static void findLoginPageObjects(
            ArrayList<DynamicMapDesignTreeNode> list,
            DynamicMapDesignTreeNode obj) {
        DynamicMapDesignTreeNode[] nodes = obj.getChildren();
        if (nodes == null) {
            return;
        }
        for (int behaviorIndex = 0; behaviorIndex <
                nodes.length; behaviorIndex++) {
            String typeName = nodes[behaviorIndex].getObject().
                    getTypeName();
            if (typeName.equals(UIObjectType.UITextBox.name()) ||
                    typeName.equals(UIObjectType.UIButton.name()) ||
                    typeName.equals(UIObjectType.UIFrame.name())) {
                list.add(nodes[behaviorIndex]);
            }
            findLoginPageObjects(list,
                    nodes[behaviorIndex]);
        }

    }

    private ArrayList<DynamicMapDesignTreeNode> sortloginPageObjects(
            ArrayList<DynamicMapDesignTreeNode> lst) {
        ArrayList<DynamicMapDesignTreeNode> lstSorted =
                new ArrayList<DynamicMapDesignTreeNode>();
        DynamicMapObject obj;
        String typeName;
        for (int i = 0; i < lst.size(); i++) {
            obj = lst.get(i).getObject();
            typeName = obj.getTypeName();
            if (!typeName.equals(UIObjectType.UIButton.name())) {
                lstSorted.add(lst.get(i));
                addBehaviors(lstSorted,
                        lst.get(i));
            }
        }
        for (int i = 0; i < lst.size(); i++) {
            obj = lst.get(i).getObject();
            typeName = obj.getTypeName();
            if (typeName.equals(UIObjectType.UIButton.name())) {
                lstSorted.add(lst.get(i));
                addBehaviors(lstSorted,
                        lst.get(i));
                break;
            }
        }
        return lstSorted;
    }
}
